//
//  HomeViewController.m
//  HuiYIn
//
//  Created by new-1020 on 2017/4/5.
//  Copyright © 2017年 new-1020. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeHeaderView.h"
#import "TitleTableViewCell.h"
#import "HomeOneCell.h"
#import "HomeCellTwo.h"
#import "AlbumListVC.h"
#import "SetViewController.h"
#import "SoundViewController.h"
#import "AlbumDetailViewController.h"
#import "SoundDetailViewController.h"
#import "SoundHistoryViewController.h"
#import "ZYShareView.h"
#import "AFNetWorking.h"
#import "UIImageView+WebCache.h"
#import "SDWebImageManager.h"
#import "AucherInfoModel.h"
#import "AlbumTotalModel.h"
#import "VoiceTotalModel.h"
#import "AlbumListModel.h"
#import "VoiceListModel.h"
#import "SeverManager.h"

#define firstCellID @"first"

#define SecondCellHeight 410
#define HeaderIconspacing SCREEN_WIDTH / 9
@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    int firstCellHeight;
}
//自定义的headerImg 用来保存首页图片的url
//@property(nonatomic,strong)NSString * headerImgUrl;

@property(nonatomic,strong)NSURL * headerImgUrl;
@property (nonatomic,strong) UIImageView *bigView;
@property(nonatomic,strong)UIButton * setButton;
@property(nonatomic,strong)UIButton * shareButton;
@property(nonatomic,strong)AucherInfoModel * aucherInfoModel;
@property(nonatomic,strong)AlbumTotalModel * albumTotalModel;
@property(nonatomic,strong)VoiceTotalModel * voiceTotalModel;
@property(nonatomic,strong)VoiceListModel * voiceListModel;
@property(nonatomic,strong)NSMutableArray<AlbumListModel *> * albumListDataArray;
@property(nonatomic,strong)NSMutableArray<VoiceListModel *> * voiceListDataArray;


@end

@implementation HomeViewController

- (void)viewDidLoad {
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],
                                                                      NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [super viewDidLoad];
    firstCellHeight = HOMEfirstCellH;
    _albumListDataArray = [[NSMutableArray alloc]init];
    _voiceListDataArray = [[NSMutableArray alloc]init];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.BaseTableView.showsVerticalScrollIndicator = false;
    [self getAucherInfo];
    [self getAlbumTotal];
    [self getVoiceTotal];
    [self getAlbumList];
    [self getVoiceList];
    [self creatUI];
    
}
#pragma mark -获取headerView和个人简介
-(void)getAucherInfo{
    //实例化sesionManager
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    //调出请求头
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //将请求头封装进去
    [manager.requestSerializer setValue:@"" forHTTPHeaderField:@"appId"];
    [manager GET:aucherInfo parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"getAucherInfo %@",responseObject);
        NSDictionary * dic = [responseObject valueForKey:@"data"];
        self.aucherInfoModel = [[AucherInfoModel alloc]initWithDict:dic];
        NSString * imageStr = [NSString stringWithFormat:@"%@%@",port,self.aucherInfoModel.faceUrl];
        NSURL * imageUrl = [NSURL URLWithString:imageStr];
//        NSLog(@"headerImgUrl%@",self.headerImgUrl);
        [self.bigView sd_setImageWithURL:imageUrl];
//        NSLog(@"首页header图片%@",imageUrl);
        self.headerImgUrl = imageUrl;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failure");
    }];
}
#pragma mark -获取专辑总数
-(void)getAlbumTotal{
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setValue:@"" forHTTPHeaderField:@"appId"];
    [manager POST:albumTotal parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.albumTotalModel = [[AlbumTotalModel alloc]initWithDict:responseObject];
        [self.BaseTableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
#pragma mark -获取声音总数
-(void)getVoiceTotal{
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setValue:@"" forHTTPHeaderField:@"appId"];
//    NSMutableDictionary * parameter = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"albumId", nil];
    //默认为0 传参获取专辑的声音总数
//    [parameter setValue:0 forKey:@"albumId"];
    [manager POST:voiceTotall parameters: nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.voiceTotalModel = [[VoiceTotalModel alloc]initWithDict:responseObject];
        [self.BaseTableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"getVoiceTotal failure");
    }];
}
#pragma mark -获取专辑列表
-(void)getAlbumList{
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setValue:@"" forHTTPHeaderField:@"appId"];
    NSDictionary * parameter = @{@"i":@0,@"size":@2};
    [manager POST:albumList parameters: parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"专辑列表%@",responseObject);
        NSArray * dataArray = [responseObject valueForKey:@"data"];
        NSLog(@"%lu",(unsigned long)dataArray.count);
        for (int i = 0; i < dataArray.count; i++) {
            NSDictionary * dic = dataArray[i];
            AlbumListModel * model = [[AlbumListModel alloc]initWithDict:dic];
            [self.albumListDataArray addObject:model];
            NSLog(@"%lu",(unsigned long)self.albumListDataArray.count);
        }
//        NSLog(@"%@",self.albumListDataArray[0]);
        [self.BaseTableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"getalbumList failure");
    }];
}
#pragma mark -获取声音列表
-(void)getVoiceList{
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setValue:@"" forHTTPHeaderField:@"appId"];
    NSDictionary * parameter = @{@"i":@0,@"size":@2};
    [manager POST:voiceList parameters:parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"声音列表%@",responseObject);
        NSArray * dataArray = [responseObject valueForKey:@"data"];
            for (int i = 0; i < dataArray.count; i++) {
                NSDictionary * dic = dataArray[i];
                VoiceListModel * model = [[VoiceListModel alloc]initWithDict:dic];
//                           NSLog(@"model的url%@",model.headerImageUrl);
                model.playID = i;
                [self.voiceListDataArray addObject:model];
        }
               [self.BaseTableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"getVoiceList failure");
    }];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

-(void)creatUI {
    HomeHeaderView * headerView = [HomeHeaderView fastLoginView];
    headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, XMH(HOMEheaderH));
    self.BaseTableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    self.BaseTableView.delegate = self;
    self.BaseTableView.dataSource = self;
    self.BaseTableView.tableHeaderView = headerView;
    [self.BaseTableView registerNib:[UINib nibWithNibName:NSStringFromClass( [TitleTableViewCell class]) bundle:nil] forCellReuseIdentifier:firstCellID];
    [self addBigView];
}
#pragma mark -头部图片
-(void)addBigView {
    self.bigView = [[UIImageView alloc]init];
    self.bigView.backgroundColor = XMColor(0, 0, 0);
    self.bigView.frame = CGRectMake(0, 0, SCREEN_WIDTH,  XMH(HOMEheaderH));
    _bigView.userInteractionEnabled = YES;
    self.shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.setButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.setButton.frame = CGRectMake(SCREEN_WIDTH * 0.77 + HeaderIconspacing, SCREEN_HEIGHT/ 18, 26, 26);
    self.shareButton.frame = CGRectMake(SCREEN_WIDTH * 0.77, SCREEN_HEIGHT/ 18, 26, 26);
    [self.shareButton setBackgroundImage:[UIImage imageNamed:@"icon_share"] forState:UIControlStateNormal];
    [self.setButton setBackgroundImage:[UIImage imageNamed:@"icon_more"] forState:UIControlStateNormal];
    [self.shareButton addTarget:self action:@selector(shareButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.setButton addTarget:self action:@selector(setButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [XMSuperHelper clipCircleFromeView:self.setButton withRadius:13];
    [XMSuperHelper clipCircleFromeView:self.shareButton withRadius:13];
    [self.bigView addSubview:self.setButton];
    [self.bigView addSubview:self.shareButton];
    [self.BaseTableView addSubview:self.bigView];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell * cell = [[UITableViewCell alloc]init];
    //个人简介
    if (indexPath.row == 0 && indexPath.section == 0) {
        TitleTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:firstCellID];
        [cell.moreButton addTarget: self action:@selector(moreButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        cell.contentLabel.text = self.aucherInfoModel.profile;
        return cell;
    }
    //专辑
    if (indexPath.row == 1 && indexPath.section == 0) {
        HomeOneCell * cell = [[NSBundle mainBundle] loadNibNamed:@"HomeOneCell" owner:nil options:nil].firstObject;
        [cell.getAllAlbumButton addTarget:self action:@selector(getAlbumButtonClick) forControlEvents:UIControlEventTouchUpInside];
    //专辑view1 view2 添加手势
        UITapGestureRecognizer *tapGeture0 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(homeAlbumViewCliked:)];
        tapGeture0.delegate = cell;
        [cell.homeAlbumViewOne addGestureRecognizer:tapGeture0];
        UIView *tapView0 = [tapGeture0 view];
        tapView0.tag = 101;
        UITapGestureRecognizer *tapGeture1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(homeAlbumViewCliked:)];
        tapGeture1.delegate = cell;
        [cell.homeAlbumViewTwo addGestureRecognizer:tapGeture1];
        UIView *tapView1 = [tapGeture1 view];
        tapView1.tag = 102;

        NSString * albumString = [NSString stringWithFormat:@"专辑(%i)",self.albumTotalModel.data];
        cell.AlbumTotalLabel.text = albumString;
        
        if (self.albumListDataArray.count > 1){
        cell.homeAlbumViewOne.AlbumCellTitleLabel.text = self.albumListDataArray[0].title;
        cell.homeAlbumViewOne.AlbumCellContentLabel.text = self.albumListDataArray[0].content;
        cell.homeAlbumViewOne.AlbumCellPlayTimesLabel.text = [NSString stringWithFormat:@"%d 万",self.albumListDataArray[0].playTimes];
        cell.homeAlbumViewOne.AlbumCellTotalNumLabel.text = [NSString stringWithFormat:@"%d 集", self.albumListDataArray[0].voiceTotal];
        NSString * imageStr0 = [NSString stringWithFormat:@"%@%@",port,_albumListDataArray[0].imgUrl];
        NSURL * imageUrl0 = [NSURL URLWithString:imageStr0];
        [cell.homeAlbumViewOne.AlbumCellImage sd_setImageWithURL:imageUrl0];
            
        cell.homeAlbumViewTwo.AlbumCellTitleLabel.text = self.albumListDataArray[1].title;
        cell.homeAlbumViewTwo.AlbumCellContentLabel.text = self.albumListDataArray[1].content;
        cell.homeAlbumViewTwo.AlbumCellPlayTimesLabel.text = [NSString stringWithFormat:@"%d 万",self.albumListDataArray[1].playTimes];
        cell.homeAlbumViewTwo.AlbumCellTotalNumLabel.text = [NSString stringWithFormat:@"%d 集", self.albumListDataArray[1].voiceTotal];
        NSString * imageStr1 = [NSString stringWithFormat:@"%@%@",port,_albumListDataArray[1].imgUrl];
        NSURL * imageUrl1 = [NSURL URLWithString:imageStr1];
        [cell.homeAlbumViewTwo.AlbumCellImage sd_setImageWithURL:imageUrl1];
        }
        return cell;
    }
    //声音
    if (indexPath.row == 2 && indexPath.section == 0) {
        HomeCellTwo * cell = [[NSBundle mainBundle] loadNibNamed:@"HomeCellTwo" owner:nil options:nil].firstObject;
         [cell.getAllVoiceButton addTarget:self action:@selector(getSoundButtonClick) forControlEvents:UIControlEventTouchUpInside];
        NSString * voiceString = [NSString stringWithFormat:@"声音(%i)",self.voiceTotalModel.data];
        cell.VoiceTotalLabel.text = voiceString;
        
//        声音view1 view2 添加手势
        UITapGestureRecognizer *tapGeture0 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(homeAlbumViewCliked:)];
        tapGeture0.delegate = cell;
        [cell.homeVoiceViewOne addGestureRecognizer:tapGeture0];
        UIView *tapView0 = [tapGeture0 view];
        tapView0.tag = 201;
        UITapGestureRecognizer *tapGeture1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(homeAlbumViewCliked:)];
        tapGeture1.delegate = cell;
        [cell.homeVoiceViewTwo addGestureRecognizer:tapGeture1];
        UIView *tapView1 = [tapGeture1 view];
        tapView1.tag = 202;

        
        if (self.voiceListDataArray.count > 1){
            cell.homeVoiceViewOne.voiceTitleLabel.text = self.voiceListDataArray[0].title;
            cell.homeVoiceViewOne.voiceClassLabel.text = self.voiceListDataArray[0].content;
            cell.homeVoiceViewOne.voiceCreateTimeLabel.text =  [self.voiceListDataArray[0].createTime substringToIndex:10];
            NSString * duration0 = [NSString stringWithFormat:@"%i:%i",self.voiceListDataArray[0].duration / 60,self.voiceListDataArray[0].duration % 60];
            cell.homeVoiceViewOne.voiceDurationLabel.text = duration0;
            cell.homeVoiceViewOne.voicePlayTimesLabel.text = [NSString stringWithFormat:@"%d 万",self.voiceListDataArray[0].playTimes];
            NSString * imageStr0 = [NSString stringWithFormat:@"%@%@",port, self.voiceListDataArray[0].imgUrl];
            NSURL * imageUrl0 = [NSURL URLWithString:imageStr0];
            [cell.homeVoiceViewOne.VoiceImageView sd_setImageWithURL:imageUrl0];
            
            cell.homeVoiceViewTwo.voiceTitleLabel.text = self.voiceListDataArray[1].title;
            cell.homeVoiceViewTwo.voiceClassLabel.text = self.voiceListDataArray[1].content;
            cell.homeVoiceViewTwo.voiceCreateTimeLabel.text = [self.voiceListDataArray[1].createTime substringToIndex:10];
            NSString * duration1 = [NSString stringWithFormat:@"%i:%i",self.voiceListDataArray[1].duration / 60,self.voiceListDataArray[0].duration % 60];
            cell.homeVoiceViewTwo.voiceDurationLabel.text = duration1;
            cell.homeVoiceViewTwo.voicePlayTimesLabel.text = [NSString stringWithFormat:@"%d万",self.voiceListDataArray[1].playTimes];
//            NSString * imageStr1 = [NSString stringWithFormat:@"%@%@",port, self.voiceListDataArray[1].imgUrl];
//            NSURL * imageUrl1 = [NSURL URLWithString:imageStr1];
            [cell.homeVoiceViewTwo.VoiceImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",port,self.voiceListDataArray[1].imgUrl]]];
        }
        return cell;
    }
    cell.backgroundColor = [XMSuperHelper XMcolorRand];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return firstCellHeight;
    }
    if (indexPath.row == 1) {
        return SecondCellHeight;
    }
    if (indexPath.row == 2) {
        return SecondCellHeight;
    }
    
    return 40;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat y = scrollView.contentOffset.y;
     if (y <= 0 ) {
        //NSLog(@"%f",y);
        CGFloat x =  y / 2;
        CGRect frame = CGRectMake(x, y, SCREEN_WIDTH - y, XMH(HOMEheaderH) - y);
        self.bigView.frame = frame;
        self.shareButton.frame = CGRectMake(0.77 * SCREEN_WIDTH - x, SCREEN_HEIGHT/ 18, 26, 26);
        self.setButton.frame = CGRectMake(0.77 * SCREEN_WIDTH + HeaderIconspacing  - x, SCREEN_HEIGHT/ 18, 26, 26);
        }
}


#pragma -mark:click
bool selected = NO ;
-(void)moreButtonClick:(UIButton *)sender{
    if (!selected) {
        CGFloat height =  [XMSuperHelper LabelHeight:textt Width:SCREEN_WIDTH - 16 Font:[UIFont systemFontOfSize:12]];
        CGFloat tempH = height - HOMElableHeigh;
        firstCellHeight += tempH > 0 ? tempH : 0;
    }else {
        firstCellHeight = HOMEfirstCellH;
    }
    [self.BaseTableView reloadData];
    selected = !selected;
}
#pragma mark -专辑 和 声音 view1 view2 手势响应事件
-(void)homeAlbumViewCliked:(UITapGestureRecognizer *)tapGesture{
    UITapGestureRecognizer *singleTap = (UITapGestureRecognizer *)tapGesture;
    NSInteger index = singleTap.view.tag;
    switch (index) {
        case 101:{
            NSLog(@"101");
        AlbumDetailViewController * vc = [[AlbumDetailViewController alloc]init];
            vc.AlbumDtailModel = self.albumListDataArray[0];
        [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case 102:{
            NSLog(@"102");
            AlbumDetailViewController * vc = [[AlbumDetailViewController alloc]init];
            vc.AlbumDtailModel = self.albumListDataArray[1];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case 201:{
        SoundDetailViewController * vc = [[SoundDetailViewController alloc]init];
            if (self.headerImgUrl) {
                vc.voiceDataArray = self.voiceListDataArray;
                vc.voiceDetailModel = self.voiceListDataArray[0];
                vc.voiceDetailModel.headerImageUrl = self.headerImgUrl;
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        }
        case 202:{
        SoundDetailViewController * vc = [[SoundDetailViewController alloc]init];
            if (self.headerImgUrl){
                vc.voiceDataArray = self.voiceListDataArray;
                vc.voiceDetailModel = self.voiceListDataArray[1];
                vc.voiceDetailModel.headerImageUrl = self.headerImgUrl;
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        }
                default:
            break;
}
}

#pragma mark -点击"所有专辑"
-(void)getAlbumButtonClick{
    AlbumListVC * vc = [[AlbumListVC alloc]init];
//    vc.albumListDataArray = self.albumListDataArray;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark -点击"所有声音"
-(void)getSoundButtonClick{
    if (self.headerImgUrl){
    SoundViewController * vc = [[SoundViewController alloc]init];
//   vc.voiceListDataArray = self.voiceListDataArray;
     vc.headerImgUrl = self.headerImgUrl;
    [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark -分享
-(void)shareButtonClicked{
    NSLog(@"分享");
}
#pragma mark -更多
-(void)setButtonClick{

    __weak typeof(self) weakSelf = self;
    
    // 创建代表每个按钮的模型
    ZYShareItem *item0 = [ZYShareItem itemWithTitle:@"分享"
                                               icon:@"more_icon_share"
                                            handler:^{ [weakSelf itemAction:1]; }];
    
    ZYShareItem *item1 = [ZYShareItem itemWithTitle:@"下载"
                                               icon:@"more_icon_downloa"
                                            handler:^{ [weakSelf itemAction:2]; }];
    
    ZYShareItem *item2 = [ZYShareItem itemWithTitle:@"播放历史"
                                               icon:@"more_icon_history"
                                            handler:^{ [weakSelf itemAction:3]; }];
    
    ZYShareItem *item3 = [ZYShareItem itemWithTitle:@"下载管理"
                                               icon:@"more_icon_ad"
                                            handler:^{ [weakSelf itemAction:4]; }];
    
    ZYShareItem *item4 = [ZYShareItem itemWithTitle:@"设置"
                                               icon:@"more_icon_set"
                                            handler:^{ [weakSelf itemAction:5]; }];
    
    NSArray *shareItemsArray = @[item0, item1, item2, item3];
    NSArray *functionItemsArray = @[item4];
    
    // 创建shareView
    ZYShareView *shareView = [ZYShareView shareViewWithShareItems:shareItemsArray
                                                    functionItems:functionItemsArray];
    // 弹出shareView
    [shareView show];
    

}
//更多按钮点击事件
- (void)itemAction:(NSInteger)number
{
    switch (number) {
        case 3:{
            SoundHistoryViewController * vc = [[SoundHistoryViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 5:
        {
            SetViewController * vc = [[SetViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            break;
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    // 白色导航栏
    return UIStatusBarStyleLightContent;
}


@end
